package com.seniorproject.aims;
import java.io.*;  

import javax.servlet.ServletContext;
import javax.servlet.ServletException;  
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;  

@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {  
	  
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		System.out.println("@DownloadServlet");
		String file_name = request.getParameter("file_name");
        String file_path = request.getParameter("file_path");
        
        System.out.println("file_path:"+file_path);
        
        File file = new File(file_path);
        
        if(!file.exists()){
            throw new ServletException("File doesn't exists on server.");
        }
        
        System.out.println("File location on server::"+file.getAbsolutePath());
        ServletContext ctx = getServletContext();
        InputStream fis = new FileInputStream(file);
        String mimeType = ctx.getMimeType(file.getAbsolutePath());
        response.setContentType(mimeType != null? mimeType:"application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + file_name + "\"");
         
        ServletOutputStream os  = response.getOutputStream();
        byte[] bufferData = new byte[1024];
        int read=0;
        while((read = fis.read(bufferData))!= -1){
            os.write(bufferData, 0, read);
        }
        os.flush();
        os.close();
        fis.close();
        System.out.println("File downloaded at client successfully");
    }
 
}  

